#include "singledictmodel.h"
#include "universalquerymodel.h"
#include <QtSql>
#include <QColor>

SingleDictModel::SingleDictModel(QString sqlTable, QObject *parent)
        : UniversalQueryModel(parent), _sqlTable(sqlTable)
{
    filterText = "";
    refresh();
}

Qt::ItemFlags SingleDictModel::flags(const QModelIndex &index) const
{
    Qt::ItemFlags flags = QSqlQueryModel::flags(index);
    return flags;
}

QVariant SingleDictModel::data(const QModelIndex &index, int role) const
{
    QVariant value = QSqlQueryModel::data(index, role);

    switch (role) {
    case Qt::DisplayRole:
            return value;
    case Qt::TextAlignmentRole:
            if (index.column() == 0)
                return int(Qt::AlignVCenter | Qt::AlignCenter);
            else
                return int(Qt::AlignVCenter | Qt::AlignLeft);
    case Qt::BackgroundColorRole:
            if  (index.column() == 0 )
               return qVariantFromValue(QColor(220,240,230));
            else
               return qVariantFromValue(QColor(246,246,250));
    }
    return value;
}

void SingleDictModel::refresh()
{
    sort(sortColumn, sortOrder);
    setHeaderData(0, Qt::Horizontal,QObject::tr("#"));
    setHeaderData(1,Qt::Horizontal, QObject::tr("Наименование"));
}

void SingleDictModel::sort(int column, Qt::SortOrder order)
{
    saveSelState();
    setQuery(fetchTableData(column, order));
    qDebug() << this->query().lastQuery();
    if (!lastError().isValid()) {
        sortColumn = column;
        sortOrder = order;
        returnSelState();
    } else {
        qDebug() << tr("Sql execute error in SingleDictModel::sort()");
        qDebug() << lastError().text();
    }
    //emit queryUpdated();
}

QString SingleDictModel::fetchTableData(int column, Qt::SortOrder order)
{
    QString filter = filterText.trimmed();
    QString query = QString("SELECT id, name FROM %1 ")
                    .arg(_sqlTable); ;
    if (filter != ""){
        query += QString(" WHERE name LIKE '%%1%'").arg(filter);
    }
    query += QString(" ORDER BY %1 %2")
             .arg(QString::number(column+1),
                  order == Qt::AscendingOrder ? "ASC" : "DESC");
    qDebug() << query <<" |";
    return query;
}

QString SingleDictModel::sqlTable() const
{
    return _sqlTable;
}

void SingleDictModel::setSqlTable(const QString &table)
{
    if (_sqlTable == "")
        _sqlTable = table;
    else
        qDebug() << "Don't change _sqlTable twice! SingleDictModel::swtSqlTable(const QString &table)";
}

void SingleDictModel::filtrate(const QString &name)
{
    filterText = name;
    refresh();
}



















